import { Api } from '@/api'
import { defineStore } from 'pinia'
import { computed, onMounted, onUnmounted, ref } from 'vue'

export const useGlobalStore = defineStore('global', () => {
  const width = ref(window.innerWidth)
  const handleResize = () => {
    width.value = window.innerWidth
    if (width.value > 750) {
      document.documentElement.setAttribute('data-device', 'web')
    }
    else {
      document.documentElement.setAttribute('data-device', 'h5')
    }
  }
  handleResize()
  onMounted(() => window.addEventListener('resize', handleResize))
  onUnmounted(() => window.removeEventListener('resize', handleResize))

  const bannerInit = ref<Eps.HomeService.GetAdvertise['Datas']>(null!)
  const wideInit = ref<Eps.HomeService.GetAdvertise['Datas']>(null!)
  const setAdvertise = () => {
    Api.HomeService.GetAdvertise({
      pageIndex: 0,
      pageSize: 100,
    }).then((res) => {
      const bArr: any = []
      const wArr: any = []
      res.Datas?.filter((item) => {
        return item.Status === 0
      }).forEach((item) => {
        if (item.Type === 1) {
          bArr.push(item)
        }
        else {
          wArr.push(item)
        }
      })
      bannerInit.value = bArr
      wideInit.value = wArr
    })
  }

  const banner = computed(() => {
    const currentWidth = width.value
    return bannerInit.value?.filter(item => currentWidth > 750 ? item.SubType === 2 : item.SubType === 1)
  })
  const wide = computed(() => {
    const currentWidth = width.value

    return wideInit.value?.filter(item => currentWidth > 750 ? item.SubType === 2 : item.SubType === 1)
  })
  return {
    width,
    banner,
    wide,
    setAdvertise,
  }
})
